package com.timo.shopp.management.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.timo.shopp.common.constants.Constants;
import com.timo.shopp.management.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Timo
 * @Date: 2019/3/24 14:47
 * @Description: redis 缓存工具
 */
@Service
public class RedisServiceImpl implements RedisService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    /**
     * 这里保存的对象都是存成了fastJSon 字符串
     * 默认保存时间为60分钟
     * @param key   键名
     * @param value 保存对象
     */
    @Override
    public void set(String key, Object value) {
        stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(value), Constants.ResiltConstantsEnum.DEFAULT_TIME.minute,TimeUnit.MINUTES);
    }


    @Override
    public void set(String key, Object value, long seconds) {
        stringRedisTemplate.opsForValue().set(key,JSONObject.toJSONString(value),seconds,TimeUnit.SECONDS);
    }

    @Override
    public void set(String key, Object value, TimeUnit timeUnit, long time) {
        stringRedisTemplate.opsForValue().set(key,JSONObject.toJSONString(value),time,timeUnit);
    }

    @Override
    public <T> void setList(String key, List<T> list) {
        set(key,list);
    }

    @Override
    public <T> List<T> getList(String key, Class<T> clz) {
        String value = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(value)){
            return null;
        }
        return (List<T>) JSONObject.parseObject(value,clz);
    }

    @Override
    public <T> T get(String key, Class<T> clz) {
        String value = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(value)){
            return null;
        }
        return JSONObject.parseObject(value,clz);
    }

    @Override
    public Boolean remove(String key) {
        return stringRedisTemplate.delete(key);
    }

    @Override
    public boolean expire(String key, long expireSeconds) {
        return expire(key,TimeUnit.SECONDS,expireSeconds);
    }

    @Override
    public boolean expire(String key, TimeUnit timeUnit, long time) {
        return stringRedisTemplate.expire(key,time,timeUnit);
    }
}
